"""
用户相关视图
"""
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from pecco_site.models import UserProfile, UserAddress
from ..serializers.user import (
    UserSerializer, UserRegisterSerializer, UserLoginSerializer,
    UserUpdateSerializer, UserProfileSerializer
)
from rest_framework import serializers

# 簡單的地址序列化器，僅用於前台
class SimpleAddressSerializer(serializers.ModelSerializer):
    full_name = serializers.ReadOnlyField(source='get_full_name')
    formatted_address = serializers.ReadOnlyField(source='get_formatted_address')
    
    class Meta:
        model = UserAddress
        fields = [
            'id', 'first_name', 'last_name', 'full_name', 'company',
            'address_line1', 'address_line2', 'city', 'state', 'postal_code',
            'country', 'phone', 'is_default', 'formatted_address'
        ]
    
    def create(self, validated_data):
        user = self.context['request'].user
        validated_data['user'] = user
        return super().create(validated_data)
    
    def update(self, instance, validated_data):
        # 確保用戶不能修改其他用戶的地址
        if instance.user != self.context['request'].user:
            raise serializers.ValidationError("You can only update your own addresses")
        return super().update(instance, validated_data)


class UserViewSet(viewsets.ModelViewSet):
    """用户视图集"""
    queryset = User.objects.all()
    serializer_class = UserSerializer
    
    def get_permissions(self):
        """根据动作设置权限"""
        if self.action in ['register', 'login']:
            return [AllowAny()]
        return [IsAuthenticated()]
    
    @action(detail=False, methods=['post'], permission_classes=[AllowAny])
    def register(self, request):
        """用户注册"""
        serializer = UserRegisterSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            
            # 生成Token
            refresh = RefreshToken.for_user(user)
            
            return Response({
                'message': 'Registration successful',
                'user': UserSerializer(user).data,
                'tokens': {
                    'refresh': str(refresh),
                    'access': str(refresh.access_token),
                }
            }, status=status.HTTP_201_CREATED)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    @action(detail=False, methods=['post'], permission_classes=[AllowAny])
    def login(self, request):
        """用户登录"""
        serializer = UserLoginSerializer(data=request.data)
        if serializer.is_valid():
            username = serializer.validated_data['username']
            password = serializer.validated_data['password']
            
            # 验证用户
            user = authenticate(username=username, password=password)
            
            if user is not None and not user.is_staff:
                # 只允许非管理员用户登录商城
                # 生成Token
                refresh = RefreshToken.for_user(user)
                
                return Response({
                    'message': 'Login successful',
                    'user': UserSerializer(user).data,
                    'tokens': {
                        'refresh': str(refresh),
                        'access': str(refresh.access_token),
                    }
                }, status=status.HTTP_200_OK)
            else:
                # 统一返回用户名或密码错误，不泄露用户是否存在或是否为管理员
                return Response({
                    'error': 'Invalid username or password'
                }, status=status.HTTP_401_UNAUTHORIZED)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    @action(detail=False, methods=['get'], permission_classes=[IsAuthenticated])
    def me(self, request):
        """获取当前用户信息"""
        serializer = UserSerializer(request.user)
        return Response(serializer.data)
    
    @action(detail=False, methods=['put', 'patch'], permission_classes=[IsAuthenticated])
    def update_profile(self, request):
        """更新用户资料"""
        serializer = UserUpdateSerializer(request.user, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'message': 'Profile updated successfully',
                'user': UserSerializer(request.user).data
            })
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    @action(detail=False, methods=['post'], permission_classes=[IsAuthenticated])
    def change_password(self, request):
        """修改密码"""
        old_password = request.data.get('old_password')
        new_password = request.data.get('new_password')
        
        if not old_password or not new_password:
            return Response({
                'error': 'Both old_password and new_password are required'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 验证旧密码
        if not request.user.check_password(old_password):
            return Response({
                'error': 'Old password is incorrect'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # 设置新密码
        request.user.set_password(new_password)
        request.user.save()
        
        return Response({
            'message': 'Password changed successfully'
        }, status=status.HTTP_200_OK)
    
    @action(detail=False, methods=['get'], permission_classes=[IsAuthenticated])
    def addresses(self, request):
        """获取用户地址列表"""
        addresses = UserAddress.objects.filter(user=request.user)
        serializer = SimpleAddressSerializer(addresses, many=True)
        return Response(serializer.data)
    
    @action(detail=False, methods=['post'], permission_classes=[IsAuthenticated])
    def add_address(self, request):
        """添加新地址"""
        serializer = SimpleAddressSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            address = serializer.save()
            return Response({
                'message': 'Address added successfully',
                'address': SimpleAddressSerializer(address).data
            }, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    @action(detail=True, methods=['put', 'patch'], permission_classes=[IsAuthenticated])
    def update_address(self, request, pk=None):
        """更新地址"""
        try:
            address = UserAddress.objects.get(id=pk, user=request.user)
        except UserAddress.DoesNotExist:
            return Response({
                'error': 'Address not found'
            }, status=status.HTTP_404_NOT_FOUND)
        
        serializer = SimpleAddressSerializer(address, data=request.data, partial=True, context={'request': request})
        if serializer.is_valid():
            address = serializer.save()
            return Response({
                'message': 'Address updated successfully',
                'address': SimpleAddressSerializer(address).data
            })
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    @action(detail=True, methods=['delete'], permission_classes=[IsAuthenticated])
    def delete_address(self, request, pk=None):
        """删除地址"""
        try:
            address = UserAddress.objects.get(id=pk, user=request.user)
        except UserAddress.DoesNotExist:
            return Response({
                'error': 'Address not found'
            }, status=status.HTTP_404_NOT_FOUND)
        
        was_default = address.is_default
        address.delete()
        
        # 如果删除的是默认地址，将第一个地址设为默认
        if was_default:
            first_address = UserAddress.objects.filter(user=request.user).first()
            if first_address:
                first_address.is_default = True
                first_address.save()
        
        return Response({
            'message': 'Address deleted successfully'
        }, status=status.HTTP_200_OK)
    
    @action(detail=True, methods=['post'], permission_classes=[IsAuthenticated])
    def set_default_address(self, request, pk=None):
        """设置默认地址"""
        try:
            address = UserAddress.objects.get(id=pk, user=request.user)
        except UserAddress.DoesNotExist:
            return Response({
                'error': 'Address not found'
            }, status=status.HTTP_404_NOT_FOUND)
        
        # 将所有地址设为非默认
        UserAddress.objects.filter(user=request.user).update(is_default=False)
        
        # 设置指定地址为默认
        address.is_default = True
        address.save()
        
        return Response({
            'message': 'Default address set successfully',
            'address': SimpleAddressSerializer(address).data
        }, status=status.HTTP_200_OK)

